package com.codecarpet.fbconnect.sample;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import temporary.CcUtil;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.codecarpet.fbconnect.FBSession;

public class StatusActivity extends Activity {
	private static final String kFeedURL = "https://graph.facebook.com/me/home";
	private static final String LOG = StatusActivity.class.getSimpleName();
	private URL _loadingURL;
	private static final String kStringBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
	protected Activity mContext;
	protected WebView _webView;
	protected FBSession mSession;
	private ListView listTimeline;
	private static final boolean WORK = false;
	private ArrayList<Status> statuses;

	// https://graph.facebook.com/me/feed
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.status);
		getStatus();
		// Find views by id
		// listTimeline = (ListView) findViewById(R.id.listTimeline);
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				getStatus();
			}
		});
		ListView view = (ListView) findViewById(R.id.listview);
		StatusAdapter sa = new StatusAdapter(this,R.layout.row, this.statuses);
		view.setAdapter(sa);

	}

	protected void getStatus() {
		InputStream in = null;
		HttpURLConnection conn = null;
		statuses = new ArrayList<Status>();
		if (!WORK) {
			FBSession _session = FBSession.getSession();
			try {
				URL url = new URL(kFeedURL + "?access_token="
						+ _session.getAccessToken());
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");

				conn.connect();
				in = conn.getInputStream();
			} catch (IOException ex) {
				ex.printStackTrace();
				System.out.println("made it here");
			}
		} else {
			try {
				in = new FileInputStream(new File("/sdcard/home.json"));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuffer sb = new StringBuffer();
		try {
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			// System.out.println(sb.toString());
			if (!WORK)
				conn.disconnect();
			System.out.println(sb.toString());

			JSONObject jobj = new JSONObject(sb.toString());
			JSONArray jarr = (JSONArray) jobj.get("data");
			for (int i = 0; i < jarr.length(); i++) {
				JSONObject jsonObject = jarr.getJSONObject(i);

				String id = jsonObject.getString("id");
				JSONObject fromObject = (JSONObject) jsonObject.get("from");
				String name = fromObject.getString("name");
				if (!fromObject.has("category")) {
					if (jsonObject.has("message")) {
						Status status = new Status();
						status.setMessage(jsonObject.getString("message"));
						status.setName(name);
						status.setTime(jsonObject.getString("created_time"));
						statuses.add(status);
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
			System.out.println("made it here");
		}

		// } catch (MalformedURLException e) {
		// e.printStackTrace();
		// }
	}

	private URL generateURL(String baseURL, Map<String, String> params)
			throws MalformedURLException {

		StringBuilder sb = new StringBuilder(baseURL);
		Iterator<Entry<String, String>> it = params.entrySet().iterator();
		if (it.hasNext()) {
			sb.append('?');
		}
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			sb.append(entry.getKey());
			sb.append('=');
			sb.append(CcUtil.encode(entry.getValue()));
			if (it.hasNext()) {
				sb.append('&');
			}
		}
		return new URL(sb.toString());
	}

	protected void loadURL(String url, String method,
			Map<String, String> getParams, Map<String, String> postParams,
			boolean sendCookies) throws MalformedURLException {

		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);

		_loadingURL = generateURL(url, getParams);

		HttpURLConnection conn = null;
		OutputStream out = null;
		InputStream in = null;
		try {
			conn = (HttpURLConnection) _loadingURL.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);

			if (method != null) {
				conn.setRequestMethod(method);
				if ("POST".equals(method)) {
					String contentType = "multipart/form-data; boundary="
							+ kStringBoundary;
					conn.setRequestProperty("Content-Type", contentType);
				}

				// Cookies are used in FBPermissionDialog and FBFeedDialog to
				// retrieve logged user
				if (sendCookies && "POST".equals(method))
					conn.setRequestProperty("Cookie", cookieManager
							.getCookie(url));

				conn.connect();

				out = conn.getOutputStream();
				if ("POST".equals(method)) {
					String body = generatePostBody(postParams);
					if (body != null) {
						out.write(body.getBytes("UTF-8"));
					}
				}
				in = conn.getInputStream();

				String response = CcUtil.getResponse(in).toString();
				if (response != "") {
					// In case there are several Set-cookie fields in the header
					for (int i = 0; true; i++) {
						String hdrKey = conn.getHeaderFieldKey(i);
						String hdrVal = conn.getHeaderField(i);
						if (hdrKey == null) {
							if (hdrVal == null)
								break; // end of the header
							continue; // in some implementations, first header
							// key is empty
						}
						Log.i(LOG, "url header: " + hdrKey + "=" + hdrVal);
						if (hdrKey.equalsIgnoreCase("set-cookie")) {
							cookieManager.setCookie(url, hdrVal);
						}
					}
					CookieSyncManager.createInstance(mContext).sync();

					URI uri = new URI(url);
					// we need to load the data with base URL or else the
					// webview doesn't know how to build relative URLs
					_webView.loadDataWithBaseURL("http://" + uri.getHost(),
							response, "text/html", "UTF-8", "http://"
									+ uri.getHost());

					// _webView.loadData(response, "text/html", "UTF-8");
				} else if (sendCookies) {
					// If the page has not loaded the first time we try to
					// reload it without sending the cookies
					// the issue is we can't delete the cookies on logout...
					loadURL(url, method, getParams, postParams, false);
				}
			}
		} catch (URISyntaxException e) {
			Log.e(LOG, "Error on url format", e);
		} catch (IOException e) {
			Log.e(LOG, "Error while opening page", e);
			// If the page has not loaded the first time we try to reload it
			// without sending the cookies
			// the issue is we can't delete the cookies on logout...
			if (sendCookies) {
				loadURL(url, method, getParams, postParams, false);
			}
		} finally {
			CcUtil.close(in);
			CcUtil.close(out);
			CcUtil.disconnect(conn);
		}

	}

	private String generatePostBody(Map<String, String> params) {
		StringBuilder body = new StringBuilder();
		StringBuilder endLine = new StringBuilder("\r\n--").append(
				kStringBoundary).append("\r\n");

		body.append("--").append(kStringBoundary).append("\r\n");

		for (Entry<String, String> entry : params.entrySet()) {
			body.append("Content-Disposition: form-data; name=\"").append(
					entry.getKey()).append("\"\r\n\r\n");
			String value = entry.getValue();
			if ("user_message_prompt".equals(entry.getKey())) {
				body.append(value);
			} else {
				body.append(CcUtil.encode(value));
			}

			body.append(endLine);
		}

		return body.toString();
	}

}
